from django.shortcuts import render
from .forms import myUserForm, FeightForm, calForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect,HttpResponse
from django.contrib.auth.decorators import login_required
from .the_fiveeight import the_res
from .models import Feight
from .func.calation import Cal
from django.contrib.auth.forms import UserCreationForm
# Create your views here.


def index(request):
    if request.method == 'POST':
        username = request.POST['uname']
        password = request.POST['pwd']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/home')
            else:
                return HttpResponseRedirect('/index')
        else:
            return HttpResponseRedirect('/index')
    else:
        res = myUserForm()
    return render(request, 'thesite/index.html', {'form':res})


def register(request):
    return HttpResponse('没法注册')


@login_required(login_url='/index')
def home(request):
    t1 = UserCreationForm()
    t = Feight.objects.values_list()
    t = list(t)
    return render(request, 'thesite/home.html', {'res': t, 'from':t1})

def logout_1(request):
    logout(request)
    if request.method == 'POST':
        username = request.POST['uname']
        password = request.POST['pwd']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/home')
            else:
                return HttpResponseRedirect('/index')
        else:
            return HttpResponseRedirect('/index')
    else:
        res = myUserForm()
    return render(request, 'thesite/index.html', {'form':res})

@login_required(login_url='/index')
def get_time(request):
    return render(request, 'thesite/get_time.html')

@login_required(login_url='/index')
def caltions(request):
    cal= Cal()
    form = calForm()
    if request.method == 'POST':
        t_form = calForm(request.POST)
        if t_form.is_valid():
            number = request.POST['number']
            choose = request.POST['choose']
            if choose != 'none':
                try:
                    t = cal.cala(number, choose)
                    return render(request, 'thesite/caltion.html', {'form':form,'res': t})
                except:
                    pass
            else:
                pass
        else:
            t = cal.cradno()
            return render(request, 'thesite/caltion.html', {'form':form,'card': t})
    return render(request, 'thesite/caltion.html',{'form':form})
